package dao.Implementation;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import Donnees.Client;
import Donnees.Commande;
import Util.HibernateUtil;
import dao.Interfaces.ICommandeDAO;

public class CommandeDAO implements ICommandeDAO {

	public CommandeDAO() {
		
	}
	
	public List<Commande> selectAll() {
		List<Commande> listeCommandes = new ArrayList<Commande>();
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		
		listeCommandes.addAll(session.createQuery("from Commande").list());
		
		session.flush();
		tx.commit();
		session.close();
		
		return listeCommandes;
	}
	
	public long insert(Commande c) {
		Commande commandeTemp = c;
		Long msgId;

		ClientDAO clientDao = new ClientDAO();
		Client cli = clientDao.getById(commandeTemp.getIdClient());

		commandeTemp.setClient(cli);
		commandeTemp.setIdClient(cli.getId());
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		msgId = (Long) session.save(commandeTemp);

		session.flush();
		tx.commit();
		session.close();

		return msgId;
	}

	public int delete(Commande c) {
		Commande commandeTemp = c;
		int retour;

		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();

		retour = session.createQuery(
				"delete from Commande where id='" + commandeTemp.getId()+ "'")
				.executeUpdate();

		session.flush();
		tx.commit();
		session.close();

		return retour;
	}
}
